/**
 * Created by wx on 2017/5/14.
 */
var Promise = require('bluebird'),
    path = require('path'),
    _ = require('lodash'),
    sendToWormhole = require('stream-wormhole'),
    fs = require('fs');

module.exports =  {
    fileupload:function (ctx,_path) {
        const stream = yield ctx.getFileStream();
        const name = _path + path.basename(stream.filename);//egg-multipart-test
        const writeStream = fs.createWriteStream(name);

        try {
            stream.on('data', function(chunk) {
                if (writeStream.write(chunk) === false) {
                    stream.pause();
                }
            });
            writeStream.on('drain', function() {
                stream.resume();
            });
            stream.on("end", function() {
                writeStream.end("The end.", function() {
                    console.log("文件全部写入完毕。");
                    console.log("共写入%d字节数据。", writeStream.bytesWritten);
                });
            });
        } catch (err) {
            // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
            yield sendToWormhole(stream);
            throw err;
        }
    }
};
